<?php

	/** Abstraction d'un adherent du club.
	 * @author Sebastian Mosser
	 * @date 2006
	 * @version 1.0
	 */

class Member implements iPersistantData, iHTMLViewable, 
											  iLookable, iXMLSerializable {


	private $_id;         ///< identifiant unique du membre
	private $_licenceNo;  ///< numero de licence attriubue par la federation
	private $_entryDate;  ///< date d'entrée dans le club

	private $_lastName;   ///< nom de famille
	private $_firstName;  ///< prenom
	private $_gender;     ///< sexe
	private $_address;    ///< adresse
	private $_livingCity; ///< ville d'habitation
	
	private $_birthDate;  ///< date de naissance
	private $_birthCity;  ///< ville de naissance
	
	private $_phone;      ///< telephone fixe
	private $_cellPhone;  ///< telephone mobile
	
	private $_picture;    ///< photo d'identite
	
	private $_clubFunctions;  ///< tableau des fonctions au sein du club
	private $_cotisations;    ///< tableau des cotisations payees

	private $_isExportable;   ///< peut on publier ce membre sur internet ?
	
	public static $EXPORTABLE     = "TRUE";
	public static $NOT_EXPORTABLE = "FALSE";
	public static $MALE = "M";
	public static $FEMALE = "F";
	public static $NO_PICTURE = "none";
	public static $PICS_DIR = "pics/";
	public static $NOBODY_PIC = "pics/nobody.jpg";
	public static $PICTURE_SIZE = 100;
	public static $PIC_HEIGHT = 100;
	public static $PIC_WIDTH = 75;
	
	public function __construct($id = -1) {
		$this->_id = $id; 
		// Initialisation des tableaux de liaisons
		$this->_clubFunctions = array();
		$this->_cotisations = array();
	}
	
	
	// On renvoi la chaine XML, on ne sait pas ou la placer
	public function xmlExport($e,$type="") {
		$infos = $this->prepare();
		$pic = $this->_picture;
		if ($pic != self::$NO_PICTURE) {
			$pic = BALLOON_DATA_FS_PATH . self::$PICS_DIR. $pic;
			$e->insertPics($pic);
		}
		
		$birthDate= htmlentities($this->_birthDate->sqlFormat());
		
		$id = htmlentities($infos["id"],ENT_COMPAT,"UTF-8");
		$licenceNo = htmlentities($infos["licenceNo"],ENT_COMPAT,"UTF-8");
		$name = htmlentities($infos["name"],ENT_COMPAT,"UTF-8");
		$entryDate = htmlentities($infos["entryDate"],ENT_COMPAT,"UTF-8");
		$category = htmlentities($infos["category"],ENT_COMPAT,"UTF-8");
		
		if ($this->_isExportable) {
			$ans = <<<EOS
	<member id="${id}">
		<licence>${licenceNo}</licence>
		<name>${name}</name>
		<birthdate>${birthDate}</birthdate>
		<category>${category}</category>
		<entrydate>${entryDate}</entrydate>
		<picture>${pic}</picture>
	</member>
EOS;
		}
		else {
			$ans = <<<EOS
	<member id="${id}" visible="none" />
EOS;
		}
		$e->insertData($type,$this->_id,$ans);
	}
		
	public function setLicenceNo($l)  {$this->_licenceNo  = $l; }
	public function setEntryDate($e)  {$this->_entryDate  = $e; }
	public function setLastName($l)   {$this->_lastName   = $l; }
	public function setFirstName($f)  {$this->_firstName  = $f; }
	public function setGender($g)     {$this->_gender     = $g; }
	public function setAddress($a)    {$this->_address    = $a; }
	public function setLivingcity($c) {$this->_livingCity = $c; }
	public function setBirthDate($b)  {$this->_birthDate  = $b; }
	public function setBirthCity($c)  {$this->_birthCity  = $c; }
	public function setPhone($p)      {$this->_phone      = $p; }
	public function setCellPhone($c)  {$this->_cellPhone  = $c; }
	public function setPicture($p)    {$this->_picture    = $p; }
	public function setExportable($b) { $this->_isExportable = $b; }
	
	/** Accès en modification au contenu des liaisons **/
	public function addFunction($season,$func) {
		$oldFunction = $this->getFunction($season);
		if ($func != $oldFunction)
		  $this->_clubFunctions["$season"] = $func;
	}
	
	public function delFunction($season) {
		unset($this->_clubFunctions["$season"]);
	}
	
	public function addCotisation($season, $cotis, $payment) {
		$c = array();
		$c["cotisation_type"] = $cotis;
		$c["payment_type"] = $payment;
		$this->_cotisations["$season"] = $c;
	}
	
	public function delCotisation($season) {
		unset($this->_cotisations["$season"]);
	}
	
	
	/** Accès en lecture au contenu **/
	public function getBirthDate() {
		return $this->_birthDate;
	}
	
	public function getGender() {
		return $this->_gender;
	}
	
	public function getBalloonId()  { return $this->_id; }
	public function getLastName()   { return $this->_lastName; }
	public function getFirstName()  { return $this->_firstName; }
	public function getBirthCity()  { return $this->_birthCity; }
	public function getAddress()    { return $this->_address; }
	public function getLivingCity() { return $this->_livingCity; }
	public function getPhone()      { return $this->_phone; }
	public function getCellPhone()  { return $this->_cellPhone; }
	public function getEntryDate()  { return $this->_entryDate; }
	public function getLicenceNo()  { return $this->_licenceNo; }
	public function getExportable() { return $this->_isExportable; }

	public function getPictureUrl() {
		$picture = "";
		if ($this->_picture == self::$NO_PICTURE )
			$picture = BALLOON_DATA_URL . self::$NOBODY_PIC;
		else if (! file_exists(BALLOON_DATA_FS_PATH . self::$PICS_DIR. $this->_picture))
			$picture = BALLOON_DATA_URL . self::$NOBODY_PIC;
		else
			$picture = BALLOON_DATA_URL . self::$PICS_DIR . $this->_picture;
		return $picture;
	}
	
	public function getPicture() { return $this->_picture; }

	// Renvoi -1 si pas de fonction
	public function getFunction($season) {
	
		// Cas fastoche : le tableau est vide :
		if (count($this->_clubFunctions) == 0)
			return -1;
			
		// Cas fastoche aussi : la saison est définie :
		if (array_key_exists($season,$this->_clubFunctions))
			return $this->_clubFunctions[$season];
		
		// Cas moins fastoche : la saison n'est pas définie directement
		// Hypothèse inductive : les saisons sont classée par ordre descendant
		$tmp = array_reverse($this->_clubFunctions,True);

		// Donc, on les retourne pour travailler facilement
		$lastId = -1;
		foreach($tmp as $k => $v) {
			if ($k > $season)
				break ; // Pas de fonction après ...
			if ($k < $season)
				$lastId = $k;
		}
		if ($lastId == -1)
			return -1;
		else
			return $this->_clubFunctions[$lastId];
	}
	
	// Renvoi -1 si pas de cotisations
	public function getCotisation($season) {
		if (array_key_exists($season, $this->_cotisations))
			return $this->_cotisations[$season];
		else
			return -1;
	}
	
	public function getExistantFunctions() {
		return $this->_clubFunctions;
	}
	
	public function getExistantCotisations() {
		return $this->_cotisations;
	}
	
	/** Implémentation de l'interface de données persistantes **/
	
	public static function createTable() {
		$myDb = Database::getSingleton();
		
		// Table de stockage des membres (principale)
		$query  = "CREATE TABLE IF NOT EXISTS `member` ( \n";
		$query .= "  `id` INTEGER  NOT NULL PRIMARY KEY auto_increment, \n";
		$query .= "  `licence_no`    VARCHAR(20) NOT NULL, \n";
		$query .= "  `entry_date`    VARCHAR(10)  NOT NULL, \n";
		$query .= "  `last_name`     VARCHAR(50)  NOT NULL, \n";
		$query .= "  `first_name`    VARCHAR(50)  NOT NULL, \n";
		$query .= "  `gender`        VARCHAR(1)   NOT NULL, \n";
		$query .= "  `address`       VARCHAR(100) NOT NULL, \n";
		$query .= "  `living_city`   INTEGER      NOT NULL, \n";
		$query .= "  `birth_date`    VARCHAR(10)  NOT NULL, \n";
		$query .= "  `birth_city`    INTEGER      NOT NULL, \n";
		$query .= "  `phone`         VARCHAR(12)  NOT NULL, \n";
		$query .= "  `cell_phone`    VARCHAR(12)  NOT NULL, \n";
		$query .= "  `picture`       VARCHAR(255) NOT NULL, \n";
		$query .= "  `is_exportable` VARCHAR(5)   NOT NULL);  ";
		$myDb->execute($query);
		
		// Table de liasons sur les fonctions
		$query  = " CREATE TABLE IF NOT EXISTS `member_club_function_lnk` ( \n";
		$query .= "  `id`      INTEGER     NOT NULL PRIMARY KEY auto_increment, \n";	
		$query .= "  `member_id`        INTEGER NOT NULL, \n";
		$query .= "  `season_id`        INTEGER NOT NULL, \n";
		$query .= "  `club_function_id` INTEGER NOT NULL);";
		$myDb->execute($query);
		
		// Table de laisons sur les cotisations
		$query = "CREATE TABLE IF NOT EXISTS `member_cotisation_lnk` (\n";
		$query .= "  `id`      INTEGER     NOT NULL PRIMARY KEY auto_increment, \n";	
		$query .= "  `season_id`     INTEGER NOT NULL, \n";
		$query .= "  `member_id`     INTEGER NOT NULL, \n";
		$query .= "  `cotisation_id` INTEGER NOT NULL, \n";
		$query .= "  `money_type_id` INTEGER NOT NULL); \n";
		$myDb->execute($query);
	
	}
	
	
	public static function dropTable() {
		$myDb = Database::getSingleton();
		$myDb->execute("DROP TABLE IF EXISTS `member`; ");
		$myDb->execute("DROP TABLE IF EXISTS `member_club_function_lnk`; ");
		$myDb->execute("DROP TABLE IF EXISTS `member_cotisation_lnk`; ");
	}
	
	public function create() {
		// /!\ COMMENTER POUR MIGRATION EAGLET 
		if ($this->_id != -1)
			throw new RuntimeException("Member/create()",
			                           "The object is still present in database");

		// Instanciation dans la table persistante : Echappement des entrées
	   $licenceNo    = Database::escape($this->_licenceNo);
	   $entryDate    = Database::escape($this->_entryDate->sqlFormat());
	   $lastName     = Database::escape($this->_lastName);
	   $firstName    = Database::escape($this->_firstName);
	   $gender       = Database::escape($this->_gender);     
	   $address      = Database::escape($this->_address);    
	   $livingCity   = Database::escape($this->_livingCity); 
	   $birthDate    = Database::escape($this->_birthDate->sqlFormat());  
	   $birthCity    = Database::escape($this->_birthCity);  
	   $phone        = Database::escape($this->_phone);      
	   $cellPhone    = Database::escape($this->_cellPhone);  
	   $picture      = Database::escape($this->_picture);
	   if ($this->_isExportable)
	     $isExportable = Database::escape(self::$EXPORTABLE);
	   else
	   	 $isExportable = Database::escape(self::$NOT_EXPORTABLE);
	   
	   
	   // MIGRATION
	   //$id = $this->_id;
	   
	   // construction de la requête
	   $query = <<<EOS
INSERT INTO `member` VALUES 
('', '$licenceNo', '$entryDate', '$lastName', '$firstName', '$gender',
 '$address', '$livingCity', '$birthDate', '$birthCity', '$phone',
  '$cellPhone', '$picture', '$isExportable'); 
EOS;
	   
	   // Injection de la requête dans le moteur de base :
	   $myDb = Database::getSingleton();
	   $ans = $myDb->executeInsert($query);
	   
	   // Mise a jour de la clé identifiante
	   $this->_id = $ans[0];
	   
	   // Injection des laisons présentes dans l'objet
	   $this->manageLnk();
	}
	
	
	public static function read($key) {
		$myDb = Database::getSingleton();
		$key = Database::escape($key);
		
		// Recuperation du membre :
		$query = "SELECT * FROM `member` WHERE `id` = $key;";
		$ans = Database::assoc($myDb->execute($query));
		
		if (! $ans)
			throw new Exception("Member/read() : Unknown key $key !",1);
			
		// chargement des membres d'instances :
		$aMember = new Member($ans["id"]);
		$aMember->setLicenceNo($ans["licence_no"]);
		$aMember->setEntryDate(Date::fromSql($ans["entry_date"]));
		$aMember->setLastName($ans["last_name"]);
		$aMember->setFirstName($ans["first_name"]);
		$aMember->setGender($ans["gender"]);
		$aMember->setAddress($ans["address"]);
		$aMember->setLivingCity($ans["living_city"]);
	  $aMember->setBirthDate(Date::fromSql($ans["birth_date"]));
	  $aMember->setBirthCity($ans["birth_city"]);
	  $aMember->setPhone($ans["phone"]);
	  $aMember->setCellPhone($ans["cell_phone"]);
	  $aMember->setPicture($ans["picture"]);
	  if ($ans["is_exportable"] == self::$EXPORTABLE)
	  	$aMember->setExportable(True);
	  else
	  	$aMember->setExportable(False);
	  	
	  // Chargement des laisons
	  // fonctions occupées dans le club 
	  $aMember->_clubFunctions = array();
	  $query = "SELECT * FROM `member_club_function_lnk`";
	  $query .= "  WHERE `member_id` = ".$aMember->_id;
 	  $query .= "  ORDER BY `season_id` DESC";
	  $ans = $myDb->execute($query);
	  while (($row = Database::assoc($ans)) != False) {
	  	$aMember->addFunction($row["season_id"],$row["club_function_id"]);
	  }
	  
	  // Cotisations payées :
	  $aMember->_cotisations = array();
	  $query = "SELECT * FROM `member_cotisation_lnk`";
	  $query .= "  WHERE `member_id` = ".$aMember->_id;
	  $query .= "  ORDER BY `season_id` DESC";
	  $ans = $myDb->execute($query);
	  while (($row = Database::assoc($ans)) != False) {
	  	$aMember->addCotisation($row["season_id"],
	  													$row["cotisation_id"],
	  													$row["money_type_id"]);
	  }
	  
	  //var_dump($aMember);
	  return $aMember;
	}
	
	public static function readYear($birthYear, $gender) {
		$myDb = Database::getSingleton();
		$birthYear = Database::escape($birthYear);
		$gender = Database::escape($gender);
		
		// Recuperation du membre :
		$query = "SELECT * FROM `member` WHERE `birth_date` LIKE '$birthYear" . "%' AND `gender` = '$gender';";
		$anso = Database::assoc($myDb->execute($query));
		$answer = mysql_query($query);
		$num = mysql_num_rows($myDb->execute($query));
		if (! $anso)
			throw new Exception("Member/readYear() : Unknown key $birthYear !",1);
		$n=0;
		while ($ans = mysql_fetch_array($answer) ) {
		
		// chargement des membres d'instances :
		$aMember[$n] = new Member($ans["id"]);
		$aMember[$n]->setLicenceNo($ans["licence_no"]);
		$aMember[$n]->setLastName($ans["last_name"]);
		$aMember[$n]->setFirstName($ans["first_name"]);
		$aMember[$n]->setGender($ans["gender"]);
		$aMember[$n]->setBirthDate(Date::fromSql($ans["birth_date"]));
		$n++;
	  
	 }
	  return $aMember;
	}
	
	public function update() {
	  if ($this->_id == -1)
			throw new RuntimeException("Member/update()",
			                           "The object isn't present in database");
		 
		// MAJ dans la table persistante : Echappement des entrées
	  $licenceNo    = Database::escape($this->_licenceNo);  
	  $entryDate    = Database::escape($this->_entryDate->sqlFormat());  
	  $lastName     = Database::escape($this->_lastName);
	  $firstName    = Database::escape($this->_firstName);
	  $gender       = Database::escape($this->_gender);     
	  $address      = Database::escape($this->_address);    
    $livingCity   = Database::escape($this->_livingCity); 
    $birthDate    = Database::escape($this->_birthDate->sqlFormat());  
	  $birthCity    = Database::escape($this->_birthCity);  
	  $phone        = Database::escape($this->_phone);      
	  $cellPhone    = Database::escape($this->_cellPhone);  
	  $picture      = Database::escape($this->_picture);
	  if ($this->_isExportable)
		  $isExportable = Database::escape(self::$EXPORTABLE);
		else
			$isExportable = Database::escape(self::$NOT_EXPORTABLE);
			
	   
	  // Construction de la requete :
	  $query  = "UPDATE `member` SET \n";
	  $query .= "  `licence_no`    = '$licenceNo',   \n";
	  $query .= "  `entry_date`    = '$entryDate' ,  \n";
		$query .= "  `last_name`     = '$lastName' ,   \n";
	  $query .= "  `first_name`    = '$firstName' ,  \n";
	  $query .= "  `gender`        = '$gender' ,     \n";
		$query .= "  `address`       = '$address' ,    \n";
		$query .= "  `living_city`   = '$livingCity',  \n";
		$query .= "  `birth_date`    = '$birthDate',   \n";
		$query .= "  `birth_city`    = '$birthCity',   \n";
		$query .= "  `phone`         = '$phone',       \n";
		$query .= "  `cell_phone`    = '$cellPhone',   \n";
		$query .= "  `picture`       = '$picture',     \n";
		$query .= "  `is_exportable` = '$isExportable' \n";
	  $query .= "  WHERE `id` = $this->_id ;";
	  
	  // Execution de la requete dans le moteur de base
	  $myDb = Database::getSingleton();
	  $myDb->execute($query);
	   
	  // Mise a jour des laisons
	  $this->manageLnk();
	}
	
	public function delete() {
		// Ne devrait jamais être apeléle, mais bon ...
		if ($this->_id == -1)
		  throw new RuntimeException("Member/delete()","non persistant object");

		$id = $this->_id;
		
		$myDb = Database::getSingleton();
		// Table principale
		$query = "DELETE FROM `member` WHERE `id` = $id ;";
		$myDb->execute($query);
		
		// Table de liaisons
		$query  = "DELETE FROM `member_club_function_lnk` WHERE `member_id` = $id";
		$myDb->execute($query);
		
		// Table de liasons
		$query  = "DELETE FROM `member_cotisation_lnk` WHERE `member_id` = $id";
		$myDb->execute($query);
	
	}
	
	public function tag() {
	 		$tmp = array();
	 		$tmp[0] = "Member";
	 		$tmp[1] = $this->_id;
	 		return $tmp;
	}
	
	public function soundsLike($o) {
		return False; // TO DO : fix me :p
	}
	 	
	
	// Gère les tables de laisons
	
	private function manageLnk() {
		$this->manageLnkFunctions();
		$this->manageLnkCotisations() ;
	}
	
	private function manageLnkFunctions() {
	
		// Récupération de la base de données
	  $myDb = Database::getSingleton();
	  $id = $this->_id;
	  
	  
	  // Récupération des infos présentes sur les fonctions :
	  $sql = "SELECT * FROM `member_club_function_lnk` WHERE `member_id` = $id";
	  $ans = $myDb->execute($sql);
	  
	  $tmpFunctions = $this->_clubFunctions;
	  
	  while (($row = Database::assoc($ans)) != False) {
	    if (array_key_exists($row["season_id"],$tmpFunctions)) {
	      // quelque chose dans la base ...
	      $volatileFunction = $tmpFunctions[$row["season_id"]];
	      $persistantFunction = $row["club_function_id"];
	      
	      if ( $volatileFunction != $persistantFunction ) {
	      	// Les données ont changée ... database update
	      	$f = Database::escape($volatileFunction);
	      	$query  = "UPDATE `member_club_function_lnk` SET \n";
	      	$query .= "  `club_function_id` = $f ";
	      	$query .= "  WHERE `id` = " . $row["id"];
	      	$myDb->execute($query);
	      } 
	     
	      // Quoi qu'il arrive, on dégage du tableau temporaire
	      unset($tmpFunctions[$row["season_id"]]);
	    }
	    else {
	    	// On n'est plus dans les fonctions du membre
	    	$query = 
	    		 "DELETE FROM `member_club_function_lnk` WHERE `id` = " . $row["id"];
	    	// On se supprime des données persistantes
	    	$myDb->execute($query);
	    }
	  } // fin du while sur member_function_lnk
	  // A ce stade, le tableau temporaire contient uniquement les fct a ajouter
	  $id = Database::escape($this->_id);
	  foreach($tmpFunctions as $k => $v) {
	  	$season = Database::escape($k);
	  	$function = Database::escape($tmpFunctions[$k]);
	  	$sql  = "INSERT INTO `member_club_function_lnk` VALUES ('', ";
	  	$sql .= "  '$id', '$season', '$function');";
	  	$myDb->execute($sql);
	  }
	  
	  // synchronisation finie !
	} // fin de manageLnkFunctions()
	
	
	private function manageLnkCotisations() {
		// Récupération de la base de données
	  $myDb = Database::getSingleton();
	  $id = $this->_id;
	  
	  
	  // Récupération des infos présentes sur les cotisations :
	  $sql = "SELECT * FROM `member_cotisation_lnk` WHERE `member_id` = $id";
	  $ans = $myDb->execute($sql);
	  
	  $tmpCotisations = $this->_cotisations;
	  
	  while (($row = Database::assoc($ans)) != False) {
	    if (array_key_exists($row["season_id"],$tmpCotisations)) {
	      // quelque chose dans la base ...
	      $volatileCotisation = $tmpCotisations[$row["season_id"]];
	      $persistantCotisation = 
	        array( "cotisation_type" => $row["cotisation_id"],
	               "payment_type"    => $row["money_type_id"]);
	      
	      if ( $volatileCotisation != $persistantCotisation ) {
	      	// Les données ont changée ... database update
	      	$cotis = Database::escape($volatileCotisation["cotisation_type"]);
	      	$money = Database::escape($volatileCotisation["payment_type"]);
	      	$query  = "UPDATE `member_cotisation_lnk` SET \n";
	      	$query .= "  `cotisation_id` = $cotis , ";
	      	$query .= "  `money_type_id` = $money ";
	      	$query .= "  WHERE `id` = " . $row["id"];
	      	$myDb->execute($query);
	      } 
	     
	      // Quoi qu'il arrive, on dégage du tableau temporaire
	      unset($tmpCotisations[$row["season_id"]]);
	    }
	    else {
	    	// On n'est plus dans les cotisations du membre
	    	$query = 
	    		 "DELETE FROM `member_cotisation_lnk` WHERE `id` = " . $row["id"];
	    	// On se supprime des données persistantes
	    	$myDb->execute($query);
	    }
	  } // fin du while sur member_function_lnk
	  // A ce stade, le tableau temporaire contient uniquement les fct a ajouter
	  $id = Database::escape($this->_id);
	  foreach($tmpCotisations as $k => $v) {
	  	$season = Database::escape($k);
	  	$cotis = Database::escape($v["cotisation_type"]);
	    $money = Database::escape($v["payment_type"]);
	  	//$function = Database::escape($tmpFunctions[$k]);
	  	$sql  = "INSERT INTO `member_cotisation_lnk` VALUES ('', ";
	  	$sql .= "  '$season', '$id', '$cotis', '$money');";
	  	$myDb->execute($sql);
	  }
	  
	  // synchronisation finie !
	} // fin de manageLnkCotisations()
	
	/** Fin de l'implementation de la persistance des données **/
	
	/** Implementation de la vision HTML **/
	public function displayLong() {
	  
	  // Recupération des données a afficher
		$display = $this->prepare();
		
	  // Affichage des données
	  $page = <<<EOS

<h2> Etat civil </h2>

<div class="member_picture">
<img src="${display["picture"]}" alt="photo de l'adhérent ${display["name"]}"/>
</div>
<p>
<ul>
	<li> <strong> Nom :               </strong> ${display["name"]} </li>
	<li> <strong> Adresse :           </strong>
		<ul> 
			<li> ${display["address"]}    </li>
			<li> ${display["livingCity"]} </li>
		</ul>
	</li>
	<li> <strong> Date de Naissance : </strong> 
				${display["birthDate"]} - ${display["birthCity"]} </li>
	<li> <strong> Genre :             </strong> ${display["gender"]} </li> 
	<li> <strong> Contacts :  </strong>
		<ul>
			<li> <em> Téléphone fixe </em> : ${display["phone"]} </li>
			<li> <em> Téléphone portable</em> : ${display["cellPhone"]} </li>
		</ul>
	</li>
</ul>
</p>
<h2> Renseignements Club </h2>
<p>
<ul>
	<li> <strong> Identifiant Balloon :     </strong> 
				<code> ${display["id"]} </code> </li>
	<li> <strong> Numéro de Licence :       </strong> 
				<code> ${display["licenceNo"]} </code> </li>
	<li> <strong> Catégorie :               </strong>
				<code> ${display["category"]} </code> </li>
	<li> <strong> Date d'entrée au club :   </strong> ${display["entryDate"]}</li>
	<li> <strong> Visible sur le site Web : </strong> 
							${display["isExportable"]} </li>
</ul>
</p>
<h2> Fonctions au sein du club </h2>
<p>
  ${display["clubFunctions"]}
</p>
EOS;

	if ( Login::isInGroup(3) || Login::isInGroup(6) || Login::isInGroup(7)) {
		$page .= <<<EOS
			<h2> Cotisations payées </h2>
			<p> ${display["cotisations"]} </p>
EOS;
	}
	return $page;
	}
	
	/** Prépare l'adhérent a être affiché.
	 * @return un tableau associatif affichable
	 */
	public function prepare() {
		
		$name = strtoupper($this->_lastName) . " " . $this->_firstName;
		$address = $this->_address;
		
		$picture = "";
		if ($this->_picture == self::$NO_PICTURE )
			$picture = BALLOON_DATA_URL . self::$NOBODY_PIC;
		else if (! file_exists(BALLOON_DATA_FS_PATH . self::$PICS_DIR. $this->_picture))
			$picture = BALLOON_DATA_URL . self::$NOBODY_PIC;
		else
			$picture = BALLOON_DATA_URL . self::$PICS_DIR . $this->_picture;
		
		$city = "";
		try {
			$aCity = City::read($this->_livingCity);
			$city = $aCity->displayShort();
		}
		catch(Exception $e) {
			unset($e);
			$city = 
				"<span class=\"error\"> Ville Inconnue [".$this->_livingCity."]</span>";
		}
		
		$birthDate = "";
		if ($this->_birthDate->isUnknownDate())
			$birthDate = "<span class=\"error\"> Inconnue </span>";
		else
			$birthDate = $this->_birthDate->prettyPrint();
		
		$birthCity = "";
		try {
			$aCity = City::read($this->_birthCity);
			$birthCity = $aCity->displayShort();
		}
		catch(Exception $e) {
			unset($e);
			$birthCity = 
				"<span class=\"error\"> Ville Inconnue </span>";
		}
		
		$gender = "";
		if ($this->_gender == self::$MALE )
			$gender = "Masculin";		
		else if ($this->_gender == self::$FEMALE )
			$gender = "Féminin";
		else
			$gender = "<span class=\"error\"> Inconnue </span>";
		
		$phone = "";
		if (strlen($this->_phone) < 12)
			$phone = "<span class=\"error\"> ? ? ? </span>";
		else {
			//$phone  = substr($this->_phone,0,3) . " " . $this->_phone[3] . " ";
			$phone  = "0" . $this->_phone[3] . " ";
			$phone .= substr($this->_phone,4,2) ." ". substr($this->_phone,6,2) . " ";
			$phone .= substr($this->_phone,8,2) ." ". substr($this->_phone,10,2);
		}
		
		$cellPhone = "";
		if (strlen($this->_cellPhone) < 12)
			$cellPhone = "<span class=\"error\"> ? ? ? </span>";
		else {
			//$cellPhone  = substr($this->_cellPhone,0,3) . " ";
			$cellPhone  = "0";
			$cellPhone .=  $this->_cellPhone[3] . " ";
			$cellPhone .= substr($this->_cellPhone,4,2) . " ";
			$cellPhone .= substr($this->_cellPhone,6,2) . " ";
			$cellPhone .= substr($this->_cellPhone,8,2) . " ";
			$cellPhone .= substr($this->_cellPhone,10,2);
		}
		
		$id = $this->_id;
		$licenceNo = "";
		if ($this->_licenceNo == "")
			$licenceNo = "<span class=\"error\"> Inconnu </span>";
		else
			$licenceNo = $this->_licenceNo;
		
		$entryDate = "";
		if ($this->_entryDate->isUnknownDate())
			$entryDate = "<span class=\"error\"> Inconnue </span>";
		else
			$entryDate = $this->_entryDate->prettyPrint();
			
		$isExportable  = ($this->_isExportable == True ? "Oui" : "Non"); 

		$category = Category::display($this->_birthDate, $this->_gender);

		// Fonctions dans le club :
		if (count($this->_clubFunctions) == 0)
			$clubFunctions = "<span class=\"error\"> Aucune fonction ! </span>";
		else {
			$clubFunctions = "<ul>";
			$i = 0;
			foreach($this->_clubFunctions as $k => $v) {
				$aSeason = Season::read($k);
				$clubFunctions .= "<li> ";
				$clubFunctions .= ($i++ == 0 ? "Depuis " : "");
				$clubFunctions .= $aSeason->displayShort() . " : ";
				$aClubFunction = ClubFunction::read($v);
				$clubFunctions .= $aClubFunction->displayShort() . "</li>\n";
			}
			$clubFunctions .= "</ul>";
		}
		
		// Cotisations dans le club :
		if (count($this->_cotisations) == 0)
			$cotisations = "<span class=\"error\"> Aucune cotisation !</span>";
		else {
			$cotisations = "<ul>";
			foreach($this->_cotisations as $k => $v) {
				$aSeason = Season::read($k);
				$cotisations .= "<li> ".$aSeason->displayShort() . " : ";
				$aCotisation = Cotisation::read($v["cotisation_type"]);
				$cotisations .= $aCotisation->displayShort() . "</li>\n";
			}
			$cotisations .= "</ul>";
		}
		
		// Renvoi du résultat
		$result = array();
		$result["name"] = $name             ; $result["address"] = $address ;
		$result["livingCity"] = $city       ; $result["birthDate"] = $birthDate ;
		$result["birthCity"] = $birthCity   ; $result["gender"] = $gender ;
		$result["phone"] = $phone           ; $result["cellPhone"] = $cellPhone ;
		$result["id"] = $id                 ; $result["licenceNo"] = $licenceNo ;
		$result["entryDate"] = $entryDate   ; $result["cotisations"] = $cotisations; 
		$result["clubFunctions"] = $clubFunctions;
		$result["isExportable"] = $isExportable ; $result["picture"] = $picture;
		$result["category"] = $category;
		
		return $result;
	}
	
	
	public function displayShort() {
			  
	  // Recupération des données a afficher
		$display = $this->prepare();
		
	  // Affichage des données
	  $page = <<<EOS

<h2> Etat civil </h2>

<div class="member_picture">
<img src="${display["picture"]}" alt="photo de l'adhérent ${display["name"]}"/>
</div>
<p>
<ul>
	<li> <strong> Nom :               </strong> ${display["name"]} </li>
	<li> <strong> Adresse :           </strong>
		<ul> 
			<li> ${display["address"]}    </li>
			<li> ${display["livingCity"]} </li>
		</ul>
	</li>
	<li> <strong> Date de Naissance : </strong> 
				${display["birthDate"]} - ${display["birthCity"]} </li>
	<li> <strong> Genre :             </strong> ${display["gender"]} </li> 
	<li> <strong> Contacts :  </strong>
		<ul>
			<li> <em> Téléphone fixe </em> : ${display["phone"]} </li>
			<li> <em> Téléphone portable</em> : ${display["cellPhone"]} </li>
		</ul>
	</li>
</ul>
</p>

<h2> Renseignements Club </h2>
<p>
<ul>
	<li> <strong> Identifiant Balloon :     </strong> 
				<code> ${display["id"]} </code> </li>
	<li> <strong> Numéro de Licence :       </strong> 
				<code> ${display["licenceNo"]} </code> </li>
	<li> <strong> Catégorie :               </strong>
				<code> ${display["category"]} </code> </li>
	<li> <strong> Date d'entrée au club :   </strong> ${display["entryDate"]}</li>
	<li> <strong> Visible sur le site Web : </strong> 
							${display["isExportable"]} </li>
</ul>
</p>
EOS;
	return $page;
	
	}
	
	public function displayInline($scriptUrl = "") {
		$display = $this->prepare();
		$result = "<td> <code>";
		if ($scriptUrl != "") {
			$result .= "<a href=\"$scriptUrl?id=".$display["id"]."\">";
			$result .= $display["licenceNo"];
			$result .= "</a>";
		}
		else
			$result .= $display["licenceNo"];
			
		$result .= "</td> <td> " . $display["name"] . "</td>" ;
		$result .= "<td> " . $display["birthDate"] ."</td>";

		return $result;
	}
	
	public function displayInlineOnClick($onClick) {
		$display = $this->prepare();
		$result = "<td> <code>";
		$result .= "<a href=\"#\" onclick=\"$onClick(".$this->_id.")\">";
		$result .= $display["licenceNo"];
		$result .= "</a> </code>";	
		$result .= "</td> <td> " . $display["name"] . "</td>" ;
		$result .= "<td> " . $display["birthDate"] ."</td>";

		return $result;
	
	}

	public function displayCheckBox() {
		$display = $this->prepare();
		$result = "<td> <code>";
		$result .= $display["licenceNo"] . "</code> </td>" ;	
		$result .= "</td> <td> " . $display["name"] . "</td>" ;
		$result .= "<td> " . $display["birthDate"] ."</td>";
		$result .= "<td> <input type=\"checkbox\" name=\"memberId[";
		$result .= $this->_id . "]\" class=\"edit\" /> </td>";

		return $result;
	
	}
	
	public function displayName() {
		return strtoupper($this->_lastName) . " " . $this->_firstName;
	}
	

	/** Fin de la vision HTML **/	
	
	
	/** Affichage d'un membre pour le secretariat **/
	public function displayInListing($number) {
		$display = $this->prepare();
		$result = "<td> $number </td>";
		$result .= "<td> ". $display["licenceNo"] ." </td>";
		$result .= "<td> ". $display["name"] ." </td>";
		$result .= "<td> ". $display["birthDate"] ." </td>";
		$result .= "<td> ". nl2br($display["address"]);
		$result .= "<br />". $display["livingCity"]." </td>";
		$result .= "<td> ". $display["phone"] ." </td>";
		$result .= "<td> ". $display["cellPhone"] ." </td>";
		return $result;
	}
	
	/** Interface de recherche **/
	
	public static function lookFor($filter) {
		if (! is_array($filter))
			return False;
		$lastName = PropRetriever::getProp($filter,"lastName");
		$licence = PropRetriever::getProp($filter,"licence");
		
		if ($lastName == "" && $licence == "")
			return False;
		
		$query = "SELECT * from `member` WHERE ";
		if ($lastName != "" && $licence != "") {
			$query .= " `last_name`  LIKE \"$lastName%\" AND ";
			$query .= " `licence_no` LIKE \"$licence%\" ";
		}
		else if ($lastName != "")
			$query .= " `last_name`  LIKE \"$lastName%\" ";
		else 
			$query .= " `licence_no` LIKE \"$licence%\" ";
		$query .= "ORDER BY `last_name` ASC ";
		$myDb = Database::getSingleton();
		return $myDb->execute($query);
	
	}
	
	public static function showResult($resultSet, $scriptUrl = "") {
		$empty = "<span class=\"error\"> Il n'y a aucun résultats </span>";
		$result = "<div align=\"center\">";
		
		if (! $resultSet)
			return $result . $empty . "</div>" ;

		$i = 0;
		
		$good = "<table class=\"resultset\">\n";
		$good .= "<tr> <th> Licence </th> <th> Nom complet </th> <th> Date de Naissance </th>\n";
		
		while (($row = Database::assoc($resultSet)) != False) {
			$i++;
			$aMember = Member::read($row["id"]);
			$good .= "<tr>" . $aMember->displayInline($scriptUrl) . "</tr>\n";
		}
		
		$good .= "</table>";
		
		if ($i == 0)
			return $result . $empty . "</div>";
		else
			return $result .$good . "</div>";
	
	}
	
	public static function howMany() {
		$sql = "SELECT COUNT(*) as `count` FROM `member`;";
		$myDb = Database::getSingleton();
		$ans = Database::assoc($myDb->execute($sql));
		return $ans["count"];
	}
	
	public static function soundsLikeExistant($lastName,$firstName,$birthDate) {
		$sql = "SELECT * FROM `member` WHERE ";
		$sql .= "  `last_name` SOUNDS LIKE \"$lastName\" AND ";
		$sql .= "  `first_name` SOUNDS LIKE \"$firstName\" AND ";
		$sql .= "  `birth_date` SOUNDS LIKE \"$birthDate\" ;";
		$myDb = Database::getSingleton();
		$ans = $myDb->execute($sql);
		if (! $ans)
			return False;
		$result = array();
		while(($row = Database::assoc($ans)) != False)
			$result[] = Member::read($row["id"]);
		return $result;
	}
	
	/** Quelques ponts Bajax utiles ... **/
	
	public static function bajax_search($array) {
		$acl = array();
		for ($i = 1; $i < 8; $i++)
			$acl[] = $i;
		Bajax::secureInvoke($acl);
	
		$filter = array();
		$filter["lastName"] = PropRetriever::getProp($array,0);
		$filter["licence"]  = PropRetriever::getProp($array,1);
		$scriptUrl = PropRetriever::getProp($array,2);
		return self::showResult(self::lookFor($filter),$scriptUrl);
	}
	
	public static function bajax_dump($array) {
		$acl = array(); $acl[] = 7;
		Bajax::secureInvoke($acl);

		$id = PropRetriever::getProp($array,0);
		return nl2br(str_replace(" ","&nbsp;",print_r(Member::read($id),True)));
	}
	
	public static function bajax_display($array) {
	  $acl = array(); $acl[] = 3; $acl[] = 7;
	  Bajax::secureInvoke($acl);
	  $id = PropRetriever::getProp($array,0);
	  if ($id == "")
	  	return;
	  	
	  $aMember = self::read($id);
	  return $aMember->displayLong();
	}
	
	/** Dump un membre en un ensemble de champs de formulaire cachés **/
	public function dumpAsHiddenForm() {
		$page  = "<input type=\"hidden\" name=\"lastName\" value=\"".$this->_lastName."\" />";
		$page .= "<input type=\"hidden\" name=\"firstName\" value=\"".$this->_firstName."\" />";
		$page .= "<input type=\"hidden\" name=\"gender\" value=\"".$this->_gender."\" />";
		$page .= "<input type=\"hidden\" name=\"birthDate\"  value=\"" . $this->_birthDate->sqlFormat()."\" />";
		$page .= "<input type=\"hidden\" name=\"birthCity\" value=\"".$this->_birthCity."\" />";
		try {
		  $aCity = City::read($this->_birthCity);
		  $zip = $aCity->getZip();
		}
		catch(Exception $e) {
			$zip = "-1";
		}
		$page .= "<input type=\"hidden\" id=\"birthZip\" name=\"birthZip\" value=\"".$zip."\" />";
		$page .= "<input type=\"hidden\" name=\"adress\" value=\"" . $this->_address."\" />";
		
		try {
		  $aCity = City::read($this->_livingCity);
		  $zip = $aCity->getZip();
		}
		catch(Exception $e) {
			$zip = "-1";
		}
		$page .= "<input type=\"hidden\" id=\"livingZip\" name=\"livingZip\" value=\"".$zip."\" />";
		$page .= "<input type=\"hidden\" name=\"livingCity\" value=\"". $this->_livingCity ."\" />";
		$page .= "<input type=\"hidden\" name=\"phone\" value=\"". "0" . substr($this->_phone,3) ."\" />";
		$page .= "<input type=\"hidden\" name=\"cellPhone\" value=\"". "0" . substr($this->_cellPhone,3) ."\" />";
		$page .= "<input type=\"hidden\" name=\"licence\" value=\"".$this->_licenceNo ."\" />";
		$page .= "<input type=\"hidden\" name=\"entryDate\" value=\"".$this->_entryDate->sqlFormat() ."\" />";
		$page .= "<input type=\"hidden\" name=\"web\" value=\"" . ($this->_isExportable ? "True" : "False") ."\" />";
		
		$funcId = $this->_clubFunctions[Login::seasonChoosen(False)];
		$page .= "<input type=\"hidden\" name=\"clubFunction\" value=\"".$funcId ."\" />";
		$cotisId = 
			PropRetriever::getArray($this->_cotisations,Login::seasonChoosen(False));
		//var_dump($cotisId);
		if (count($cotisId) != 0) {
			$page .= "<input type=\"hidden\" name=\"cotisation\" value=\"". $cotisId["cotisation_type"] ."\" />";
			$page .= "<input type=\"hidden\" name=\"moneyType\" value=\"". $cotisId["payment_type"] ."\" />";
		}
		else {
			$page .= "<input type=\"hidden\" name=\"cotisation\" value=\"-1\" />";
			$page .= "<input type=\"hidden\" name=\"moneyType\" value=\"-1\" />";
		}
		return $page;
	}
	
	
	public static function getOnFunction($functionArray,$seasonId) {
		$members = self::lookFor(array("lastName" => "%"));
		$result = array();
		
		foreach($functionArray as $k => $v)
			$result[$v] = array();
			
		while (($row = Database::assoc($members)) != False) {
			$aMember = self::read($row["id"]);
			foreach($functionArray as $k => $v) {
				if ($aMember->getFunction($seasonId) == $v) {
					$result[$v][$aMember->_id] = 
						strtoupper($aMember->_lastName) . " " . $aMember->_firstName;
				}
			}
		}
		return $result;	
	}
	
	public static function getAsList($memberArray,$selected) {
		$content = "";
		foreach($memberArray as $k => $v) {
			$s = (($selected == $k) ? "selected" : "");
			$content .= "<option value=\"$k\" $s> $v </option> \n";
		}
		return $content;
	}
	
	// Renvoi un "id" sur une "licence"
	public static function getOnLicence($licenceNo) {
		
		$licenceNo = Database::escape($licenceNo);
		$sql = "SELECT `id` FROM `member` WHERE `licence_no` = $licenceNo;";
		
		$myDb = Database::getsingleton();
		$ans = $myDb->execute($sql);
		
		if (! $ans)
			return -1;
		
		$row = Database::assoc($ans);
		return $row["id"];
			
	}
	
	
} // fin de la classe

?>